package com.example.administrator.democ;

import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity implements InOnChangeListener{
    private TextView txtTime;
    private TimeReceiver timeReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtTime = findViewById(R.id.txt_time);

        updateTime();

        timeReceiver = new TimeReceiver(MainActivity.this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        registerReceiver(timeReceiver,filter);
    }

    //更新时间
    public void updateTime() {
        //获取系统当前的时间
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR);
        int minute = calendar.get(Calendar.MINUTE);

        StringBuffer buffer = new StringBuffer();
        if(hour < 10){
            buffer.append("0");
        }
        buffer.append(hour).append(":");
        if(minute < 10){
            buffer.append("0");
        }
        buffer.append(minute);
        txtTime.setText(buffer);
    }
}
